package com.hundsun.epay.autosimu.api.dom.java;

public class JavaDomUtils {
	/**
	 * 计算在java中文件编写的类型名
	 * @param compileUnit
	 * @param type
	 * @return
	 */
	public static String calculateTypeName(CompilationUnit compileUnit, FullyQualifiedJavaType type){
		if(!type.getTypeArguments().isEmpty()){
			return calculateParameterizedTypeName(compileUnit, type);
		}
		if(compileUnit == null
				|| typeDoesNotRequiredImport(type)
				|| typeIsAlreadyImported(compileUnit, type)
				|| typeIsInSamePackage(compileUnit, type)){
			return type.getShortName();
		}else{
			return type.getFullyQualifiedName();
		}
	}
	
	private static String calculateParameterizedTypeName(CompilationUnit compileUnit, FullyQualifiedJavaType type){
		String baseTypeName = calculateTypeName(compileUnit, new FullyQualifiedJavaType(type.getFullyQualifiedNameWithoutTypeParameters()));
		StringBuilder sb = new StringBuilder();
		sb.append(baseTypeName);
		
		sb.append("<");
		boolean first = true;
		for (FullyQualifiedJavaType typeParameter : type.getTypeArguments()) {
			if(first){
				first = false;
			}else{
				sb.append(", ");
			}
			sb.append(calculateTypeName(compileUnit, typeParameter));
		}
		sb.append(">");
		return sb.toString();
	}
	
	/**
	 * 判断type是否需要import
	 * @param type
	 * @return
	 */
	private static boolean typeDoesNotRequiredImport(FullyQualifiedJavaType type){
		return type.isPrimitiveType() || !type.isExplicityImported();
	}
	
	private static boolean typeIsInSamePackage(CompilationUnit compileUnit, FullyQualifiedJavaType type){
		return type.getPackageName().equals(compileUnit.getType().getPackageName());
	}
	
	private static boolean typeIsAlreadyImported(CompilationUnit compileUnit, FullyQualifiedJavaType type){
		return compileUnit.getImportedType().contains(new FullyQualifiedJavaType(type.getFullyQualifiedNameWithoutTypeParameters()));
	}
}
